package tabbar

import (
	"errors"
	"public_security/databases"
	"public_security/models"
	"time"
)

func Create(req *models.Tabbar) error {
	req.CreateTime = time.Now().Format("2006-01-02 15:04:05")
	req.Status = 2
	if err := databases.DbDefault.Model(&models.Tabbar{}).Create(req).Error; err != nil {
		return err
	}
	return nil
}

func Update(req *models.Tabbar) error {
	if err := databases.DbDefault.Model(&models.Tabbar{}).Where("id=?", req.Id).Updates(map[string]interface{}{
		"name":           req.Name,
		"address":        req.Address,
		"tabbar_type_id": req.TabbarTypeId,
		"status":         req.Status,
	}).Error; err != nil {
		return err
	}
	return nil
}

func Remove(req *models.Tabbar) error {
	var count int
	databases.DbDefault.Model(&models.Tabbar{}).Select("count(id)").Where("id=? and status=2", req.Id).Scan(&count)
	if count > 0 {
		return errors.New("已上架的导航，不支持删除")
	}
	if err := databases.DbDefault.Model(&models.Tabbar{}).Where("id=?", req.Id).Delete(req).Error; err != nil {
		return err
	}
	return nil
}

func Query(req *models.Tabbar) []*models.Tabbar {
	arts := make([]*models.Tabbar, 0)
	db := databases.DbDefault.Model(req)
	if req.TabbarTypeId != 0 {
		db = db.Where("tabbar_type_id=?", req.TabbarTypeId)
	}
	if req.Status != 0 {
		db = db.Where("status=?", req.Status)
	}
	db.Order("create_time asc").Preload("TabbarType").Find(&arts)
	return arts
}

func CreateType(req *models.TabbarType) error {
	if err := databases.DbDefault.Model(&models.TabbarType{}).Create(req).Error; err != nil {
		return err
	}
	return nil
}

func UpdateType(req *models.TabbarType) error {
	if err := databases.DbDefault.Model(&models.TabbarType{}).Where("id=?", req.Id).Updates(map[string]interface{}{"name": req.Name}).Error; err != nil {
		return err
	}
	return nil
}

func RemoveType(req *models.TabbarType) error {
	var count int
	databases.DbDefault.Model(&models.Tabbar{}).Select("count(id)").Where("tabbar_type_id=?", req.Id).Scan(&count)
	if count > 0 {
		return errors.New("正在使用的导航分类，不支持删除")
	}
	if err := databases.DbDefault.Model(&models.TabbarType{}).Where("id=?", req.Id).Delete(req).Error; err != nil {
		return err
	}
	return nil
}

func QueryType(req *models.TabbarType) []*models.TabbarType {
	arts := make([]*models.TabbarType, 0)
	db := databases.DbDefault.Model(req)
	db.Order("id asc").Find(&arts)
	return arts
}
